<template>
    <div>
        <div v-show="activeStatu">
            <el-card class="box">
                <!-- 搜索筛选名称或标题 -->
                <div class="search-container">
                    <div class="flex">
                        <div class="search-label">门店名称</div>
                        <div class="time_top">电话</div>
                    </div>
                    <div class="flexBox">
                        <div> 
                            <el-input v-model.trim="inputed" @input="filters" placeholder="输入内容" class="search-input">
                                <template #prefix>
                                    <el-icon class="el-input__icon">
                                        <search />
                                    </el-icon>
                                </template>
                            </el-input>
                        </div>
                        <div class="ml-5">
                            <el-input v-model.trim="tel" @input="filters" placeholder="输入手机号" class="search-input">
                                <template #prefix>
                                    <el-icon class="el-input__icon">
                                        <search />
                                    </el-icon>
                                </template>
                            </el-input>
                        </div>
                    </div>
                    <div class="mb-10"></div>
                    <!-- table表格数据展示 -->
                    <div> 
                        <el-table :data="activeList.slice((currentPage - 1) * pageSize, currentPage * pageSize)"
                            class="data-table" :cell-style="{ 'text-align': 'center' }" lazy="true"
                            v-el-table-infinite-scroll="handleTableScroll"
                            :header-cell-style="{ 'text-align': 'center' }" @selection-change="handleSelectionChange">
                            <el-table-column type="selection" fixed="left" />
                            <el-table-column prop="id" label="序号" fixed="left" />
                            <el-table-column prop="title" min-width="120" label="门店名称" show-overflow-tooltip />
                            <el-table-column prop="" min-width="120" label="门店状态">
                                <template #default="scope">
                                    <div class="handle">
                                        <el-switch @change="funstatus(scope.row)"
                                            :model-value="scope.row.status == 1 ? true : scope.row.status == 0 ? false : scope.row.status"
                                            inline-prompt />
                                    </div>
                                </template>
                            </el-table-column>
                            <el-table-column prop="imgs" label="图片" width="130">
                                <template #default="scope">
                                    <div>
                                        <el-image class="table-image" :src="testName + scope.row.img"
                                            :zoom-rate="1.2" :max-scale="7" :min-scale="0.2"
                                            :preview-src-list="[testName + scope.row.img]" :initial-index="4"
                                            fit="cover" preview-teleported />
                                    </div>
                                </template>
                            </el-table-column>
                            <el-table-column prop="address" min-width="120" label="门店地址" show-overflow-tooltip />
                            <el-table-column prop="tel" min-width="120" show-overflow-tooltip label="门店电话" />
                            <el-table-column prop="money" sortable label="评分" width="100">
                                <template #default="scope">
                                </template>
                            </el-table-column>

                            <el-table-column prop="createtime" width="170" label="创建时间" />
                            <el-table-column label="操作" width="130" fixed="right">
                                <template #default="scope">
                                    <div class="handle">
                                        <div @click="edit(scope.row)"
                                            class="edit-btn">编辑</div>
                                    </div>
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>
                    <div class="paging">
                        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
                            :page-sizes="[5, 10, 20, 50]" :small="small" :disabled="disabled" background
                            layout="total, sizes, prev, pager, next, jumper" :total="activeList.length" />
                    </div>
                    <!-- 删除弹窗 -->
                    <el-dialog title="删除" v-model="centerDialogVisible" width="30%" center>
                        <div class="dialog-content">确认删除该游玩吗?</div>
                        <div class="dialog-footer">
                            <el-button @click="centerDialogVisible = false">取 消</el-button>
                            <el-button type="primary" @click="deleteid">确 定</el-button>
                        </div>
                    </el-dialog>
                </div>
                <el-dialog v-model="shows" title="是否要删除" center width="20vw">
                    <el-button @click="shows = false">取 消</el-button>
                    <el-button type="primary" @click="oks">确 定</el-button>
                </el-dialog>
                <!-- 批量删除 -->
                <el-dialog title="批量删除" v-model="centerDialogVisiblet" width="30%" center>
                    <div class="dialog-content">确认删除这批数据吗?</div>
                    <span slot="footer" class="dialog-footer">
                        <div></div>
                        <div>
                            <el-button @click="centerDialogVisiblet = false">取 消</el-button>
                            <el-button type="primary" @click="deleteid_t">确 定</el-button>
                        </div>
                    </span>
                </el-dialog>
            </el-card>
        </div>

        <!-- 第二块 -->
        <div v-show="activeStatud" class="edit-container">
            <el-card class="edit-card">
                <div class="edit-title">编辑</div>
                <div class="divider"></div>
                <div class="form-container">
                    <el-form ref="ruleFormRef" class="form-wrapper" :model="ruleForm" status-icon :rules="rules"
                        label-position="left" label-width="auto">
                        <div class="form-row">
                            <div class="form-col">
                                <el-form-item label="门店名称" prop="name" class="form-item">
                                    <el-input v-model.trim="ruleForm.name" placeholder="请输入" class="full-width-input" />
                                </el-form-item>
                                <el-form-item label="门店类型" prop="option" class="form-item">
                                    <el-select v-model="ruleForm.option" placeholder="请选择" class="full-width-input">
                                        <el-option v-for="item in options" :key="item.id" :label="item.title"
                                            :value="item.id" />
                                    </el-select>
                                </el-form-item>
                                <el-form-item label="店铺评分" prop="dpdz" class="form-item">
                                    <el-rate v-model="ruleForm.dpdz" allow-half class="full-width-input" />
                                </el-form-item>
                                <el-form-item label="门店电话" prop="jqfl" class="form-item">
                                    <el-input v-model.number="ruleForm.jqfl" placeholder="请输入" class="phone-input"
                                        type="number" @input="ruleForm.jqfl = $event.replace(/[^\d]/g, '')"
                                        maxlength="11" />
                                </el-form-item>
                                <el-form-item label="营业时间" prop="businessHours" class="form-item">
                                    <el-time-picker v-model="ruleForm.businessHours" is-range range-separator="至"
                                        start-placeholder="开始时间" end-placeholder="结束时间" placeholder="选择营业时间范围"
                                        format="HH:mm:ss" value-format="HH:mm:ss" class="full-width-input" />
                                </el-form-item>
                                <el-form-item label="门店地址" prop="jqdh" class="form-item">
                                    <el-input v-model.trim="ruleForm.jqdh" placeholder="请输入" class="full-width-input" />
                                </el-form-item>
                                <el-form-item label="简短地址" prop="yysj" class="form-item">
                                    <el-input v-model.trim="ruleForm.yysj" placeholder="请输入" class="full-width-input" />
                                </el-form-item>
                                <el-form-item label="地址指引" prop="dzzy" class="form-item">
                                    <el-input v-model.trim="ruleForm.dzzy" placeholder="请输入" class="full-width-input" />
                                </el-form-item>
                                <el-form-item label="门店标签" prop="mdbq" class="form-item">
                                    <el-input v-model.trim="ruleForm.mdbq" placeholder="请输入" class="full-width-input" />
                                </el-form-item>
                                <!-- 单图封面图片 -->
                                <el-form-item prop="covers" label="门店封面">
                                    <el-upload list-type="picture-card" accept=".jpeg,.png,.jpg,.bmp,.gif"
                                        :on-preview="handlePictureCardPreviewt" :on-remove="handleRemovet"
                                        :file-list="fileListt" :before-upload="beforeAvatarUploadt">
                                        <el-icon>
                                            <Plus />
                                        </el-icon>
                                    </el-upload>
                                </el-form-item>
                                <el-form-item prop="switch" label="上下架">
                                    <el-switch @change="funstate()" v-model="ruleForm.switch" />
                                </el-form-item>
                            </div>
                            <div class="form-col">
                                <!-- 多图片上传   -->
                                <el-form-item prop="img" label="门店轮播">
                                    <el-upload list-type="picture-card" accept=".jpeg,.png,.jpg,.bmp,.gif"
                                        :on-exceed="exceed_li" :on-preview="handlePictureCardPreview"
                                        :on-remove="handleRemove" :file-list="fileList" :on-change="handleChange"
                                        :on-success="handleSuccess" :before-upload="beforeUpload" :auto-upload="false"
                                        :limit="4">
                                        <el-icon>
                                            <Plus />
                                        </el-icon>
                                    </el-upload>
                                </el-form-item>
                                <el-form-item label="经度" prop="jd" class="form-item">
                                    <el-input v-model.trim="ruleForm.jd" placeholder="请输入" class="full-width-input" />
                                </el-form-item>
                                <el-form-item label="维度" prop="wd" class="form-item">
                                    <el-input v-model.trim="ruleForm.wd" placeholder="请输入" class="full-width-input" />
                                </el-form-item>
                                <el-form-item label="店铺地址" prop="" class="form-item">
                                    <div class="map-search-container">
                                        <el-input id="tipinput" v-model.trim="searchKeyword" placeholder="请输入关键字"
                                            clearable class="map-search-input" />
                                        <el-button type="primary" class="ml-2"
                                            @click="searchs">搜索</el-button>
                                    </div>
                                    <div id="container" class="map-container"></div>
                                </el-form-item>
                            </div>
                        </div>
                        <div class="mb-8"></div>
                    </el-form>
                    <div class="form-actions">
                        <el-button type="primary" @click="submitForm(ruleFormRef)">确认</el-button>
                        <el-button @click="closes(ruleFormRef)">取消</el-button>
                    </div>
                </div>
            </el-card>
        </div>
        <el-dialog v-model="dialogVisible">
            <img class="dialog-image" :src="dialogImageUrl" alt="Preview Image" />
        </el-dialog>
        <el-dialog v-model="dialogVisiblet">
            <img class="dialog-image" :src="dialogImageUrlt" alt="Preview Image" />
        </el-dialog>
    </div>

</template>
<script setup lang="ts">
import { ref, reactive, onUpdated } from 'vue';
import { activeDel } from '../../../api/active/index';
import { lark_list } from '../../../api/group/index'
import { lark_list_shop, lark_list_shop_edit } from '../../../api/arklist/index'
import { ElMessage, ElCard, ElDropdown } from 'element-plus';
import { scenicUpload } from '../../../api/uploading/index';
const dialogVisible = ref(false);
// 搜索手机号值
const tel = ref('')
// switch开关事件
const stattess = ref('')
const funstate = () => {
    console.log(ruleForm.switch);
    if (ruleForm.switch == true) {
        stattess.value = '1'
    } else if (ruleForm.switch == false) {
        stattess.value = '0'
    }
}
// 地图引入
// 引入高德地图API
import { load } from "@amap/amap-jsapi-loader";
// 用户输入的地点关键字
const searchKeyword = ref("");
let map = null; //初始化地图
let placeSearch = null; // 声明placeSearch变量
let lati = ref('');
let longi = ref('');
onUpdated(async () => {
    // 设置高德地图的安全配置【此处一定要配置，否则会搜索失败】
    window._AMapSecurityConfig = {
        securityJsCode: "34068d35a8585449adcfdfc5b28b5006",
    };
    // 初始化地图
    map = await initMap();
    // 加载插件并绑定事件
    ({ placeSearch } = await loadPluginsAndBindEvents(map)); // 返回并解构出placeSearch
});
// 初始化高德地图实例
async function initMap() {
    // 加载高德地图API，包括指定的版本和插件
    const defaultCenter = [113.85, 35.30];
    const AMap = await load({
        key: "635f2e7ebbd699fa68ef6fad1494f713", // 高德地图API Key
        version: "2.0",
        plugins: ["AMap.PlaceSearch", "AMap.AutoComplete"],
        zoom: 10,
        center: [longi.value, lati.value]
    });
    // 创建地图实例，设置容器ID和允许自适应窗口大小
    return new AMap.Map("container", {
        resizeEnable: true,
        viewMode: "2D",
        zoom: 11,
        center: longi.value && lati.value
            ? [parseFloat(longi.value), parseFloat(lati.value)]
            : defaultCenter,
    });
}
// 加载插件并绑定事件
async function loadPluginsAndBindEvents(map) {
    const autoOptions = {
        input: "tipinput", //绑定到输入框的ID
    };
    // 创建自动完成实例
    const auto = new AMap.AutoComplete(autoOptions);
    // 创建地点搜索实例，关联到地图
    const ps = new AMap.PlaceSearch({
        map: map,
    });
    // 绑定自动完成的选中事件，根据选中的地点设置城市并执行搜索
    auto.on("select", (e) => {
        ps.setCity(e.poi.adcode); //设置搜索城市为选中地点的城市编码
        ps.search(e.poi.name); //搜索选中地点的名称
    });
    // 地图点标记
    map.on('click', function (e) {
        ruleForm.latitude = e.lnglat.getLng();
        ruleForm.longitude = e.lnglat.getLat();
    });
    if (longi.value && lati.value) {
        const marker = new AMap.Marker({
            position: [parseFloat(longi.value), parseFloat(lati.value)],
        });
        map.add(marker);
    }
    return { placeSearch: ps }; // 返回placeSearch实例
}
// 点击搜索
const searchs = () => {
    // 判断用户是否输入了关键字
    if (!searchKeyword.value.trim()) {
        ElMessage.error("请输入搜索内容！");
        return;
    }
    // 执行地点搜索，并处理搜索结果
    placeSearch.search(searchKeyword.value, (status, result) => {
        console.log(status, result);
        console.log(result.poiList.pois[0].location.lat);
        ruleForm.longitude = result.poiList.pois[0].location.lat
        ruleForm.latitude = result.poiList.pois[0].location.lng

        if (status === "complete" && result.info === "OK") {
            // 如果搜索成功且有搜索结果
            if (result.poiList.pois.length > 0) {
                // 取第一个搜索结果，设置地图中心和缩放级别
                const poi = result.poiList.pois[0];
                map.setCenter([poi.location.lng, poi.location.lat]);
                map.setZoom(15); //缩放级别
            } else {
                ElMessage.error("未找到相关地点！");
            }
        } else {
            ElMessage.error("搜索失败！");
        }
    });
}
// 创建数据变量
const activeList = ref([]);
const activeStatu = ref(true)
const activeStatud = ref(false)
import { inject } from 'vue'
import { status } from 'nprogress';
import { log } from 'console';
// 全局域名使用
const testFn = inject('testFn')
testFn()
const testName = inject('testName')
const dialogTableVisible = ref(false);
const statused = ref('1');
// 表格页码数
const inputed = ref('');
const pageSize = ref(5);
const currentPage = ref(1);
const copyList = ref([]);
const files = ref(false);
// 请求接口并开局渲染
let tokens = JSON.parse(localStorage.getItem('tokens'));
console.log(tokens);
// 编辑评分值
const value_f = ref()
// 搜索框下拉
const value = ref('')
const options = ref([])
// 请求列表渲染
render();
function render() {
    lark_list_shop({
        token: tokens.token,
        uid: tokens.userinfo.id
    }, {
        userid: tokens.userinfo.id,
        uid: tokens.userinfo.id
    }).then((res) => {
        console.log(res);
        activeList.value = res.data;
        copyList.value = res.data;
    });
    lark_list({
        token: tokens.token,
        uid: tokens.userinfo.id
    }, {
        userid: tokens.userinfo.id
    }).then((res) => {
        console.log(res);
        options.value = res.data
    });

}

// 上传图片返回路径
const fileImg = ref([])
const Delete = ref('')
const fileList = ref([])
const fileListQW = ref([])
// 照片移除后的数据
const fileremover = ref([])
const iitimg = ref([])
// 图片移除
// 图片移除
const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
    console.log(uploadFile)
    console.log(uploadFiles)
    if (uploadFiles.length < 1) {
        ruleForm.img = ''
    }
    const formData = new FormData();
    formData.append('file', uploadFile.raw);
    scenicUpload(formData).then(res => {
        console.log(res.data.url);
        for (let i = 0; i < iitimg.value.length; i++) {
            if (iitimg.value[i] == res.data.url) {
                iitimg.value.splice(i, 1)
                break;
            }
        }
    })

    for (let i = 0; i < iitimg.value.length; i++) {
        if (iitimg.value[i] == uploadFile.url.slice(testName.length, 106)) {
            iitimg.value.splice(i, 1)
            break;
        }
    }
    console.log(iitimg.value);
}
const dialogImageUrl = ref('')
const dialogVisiblet = ref(false)
const dialogImageUrlt = ref('')
// 图片放大视图
const handlePictureCardPreview = (file) => {
    // console.log(file.raw.name);
    dialogImageUrl.value = file.url;
    dialogVisible.value = true;
}
const imgList = ref([])
// 图片超出限制
const exceed_li = () => {
    ElMessage({
        message: '最多可上传四张',
        type: 'warning',
    })
}
// 图片上传回调函数
const handleChange = (file, fileLists) => {
    const fileName = file.name
    const fileType = fileName.substring(fileName.lastIndexOf('.'))
    const formData = new FormData();
    formData.append('file', file.raw);
    scenicUpload(formData).then(res => {
        console.log(res.code);
        if (res.code == 1) {
            ruleForm.img = res.data.url
            console.log(res.data, '上传成功');
            fileImg.value.push(res.data.url)
            fileremover.value.push(res.data.url)
            imgList.value.push(res.data.url.split(','))
            iitimg.value.push(res.data.url)
        } else if (res.code == 0) {
            ElMessage.error('图片不能大于2MB!')
            for (let i = 0; i < fileLists.length; i++) {
                if (i === fileLists.length - 1) {
                    fileLists.splice(i, 1)
                }
            }
        }
    })
    // }
    // jpeg,.png,.jpg,.bmp,.gif
    if (
        fileType === '.jpg' ||
        fileType === '.png' ||
        fileType === '.jpeg' ||
        fileType === '.bmp' ||
        fileType === '.gif'
    ) {
    } else {
        ElMessage.error('不是,jpeg,.png,.jpg,.bmp,.gif文件,请上传正确的图片类型')
        return false
    }
    console.log(file);
    console.log(file.raw);
};
// success成功回调函数 图片
const handleSuccess = (response, file, fileList) => {
    console.log('File uploaded successfully:', response, file, fileList);
    console.log(fileImg.value);
};

const beforeUpload = (rawFile) => {
    console.log(rawFile);
    console.log(1);

    if (rawFile.type !== 'image/jpeg') {
        ElMessage.error('Avatar picture must be JPG format!')
        return false
    } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('Avatar picture size can not exceed 2MB!')
        return false
    }
    return true
}


const fileListt = ref([]);
const handlePictureCardPreviewt = (file) => {
    // console.log(file.raw.name);
    dialogImageUrlt.value = file.url;
    dialogVisiblet.value = true;
}
// 图片移除
const handleRemovet = (file, fileListt) => {
    console.log(file, fileListt);
    if (fileListt.length < 1) {
        ruleForm.covers = ''
    }
};
// 图片上传回调事件
const beforeAvatarUploadt = (file) => {
    const fileName = file.name
    const fileType = fileName.substring(fileName.lastIndexOf('.'))
    // jpeg,.png,.jpg,.bmp,.gif
    if (
        fileType === '.jpg' ||
        fileType === '.png' ||
        fileType === '.jpeg' ||
        fileType === '.bmp' ||
        fileType === '.gif'
    ) {
    } else {
        ElMessage.error('不是,jpeg,.png,.jpg,.bmp,.gif文件,请上传正确的图片类型')
        return false
    }
    console.log(file);
    // 压缩图片
    compressImage(file).then(compressedBlob => {
        const formData = new FormData();
        formData.append('file', compressedBlob, file.name);
        if (file.size / 1024 / 1024 > 2) {
            console.log(file.size / 1024 / 1024);
            ElMessage.error('图片不能大于2MB!')
            return false
        } else {
            console.log(formData);
            scenicUpload(formData).then(res => {
                console.log(res);
                // fileImg.cover = res.data.url
                fileListt.value = [{
                    name: 'plant-1.png',
                    url: testName + res.data.url,
                }]
                ruleForm.covers = res.data.url
            })
        }
    });
    return false; // 阻止默认上传行为
}
const compressImage = (file) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    return new Promise((resolve) => {
        reader.onload = e => {
            const img = new Image();
            img.src = e.target.result;
            img.onload = () => {
                const canvas = document.createElement('canvas');
                const ctx = canvas.getContext('2d');
                const { width, height } = img;
                canvas.width = width;
                canvas.height = height;
                ctx.drawImage(img, 0, 0, width, height);
                // 可以在这里调整压缩质量和尺寸
                const quality = 0.7; // 压缩质量
                const newImageData = canvas.toDataURL('image/jpeg', quality);
                const resizedBlob = dataURLtoBlob(newImageData);
                console.log(ctx);
                resolve(resizedBlob);
            };
        };
    });
};
const dataURLtoBlob = (dataurl) => {
    const arr = dataurl.split(',');
    const mime = arr[0].match(/:(.*?);/)[1];
    const bstr = atob(arr[1]);
    let n = bstr.length;
    const u8arr = new Uint8Array(n);
    while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
    }
    return new Blob([u8arr], { type: mime });
};

let g = ''
// 获取到当前时间
function getCurrentDateTimeString() {
    const now = new Date();
    // 获取当前的年份，并只取后两位
    const year = now.getFullYear().toString().slice();
    // 获取当前的月份，并确保是两位数（从0开始）
    const month = (now.getMonth() + 1).toString().padStart(2, '0');
    // 获取当前的日期，并确保是两位数
    const day = now.getDate().toString().padStart(2, '0');
    // 获取当前的小时，并确保是两位数
    const hours = now.getHours().toString().padStart('0');
    // 获取当前的分钟，并确保是两位数
    const minutes = now.getMinutes().toString().padStart(2, '0');
    // 获取当前的秒，并确保是两位数
    const seconds = now.getSeconds().toString().padStart(2, '0');
    // 拼接成所需的字符串格式
    const dateTimeString = `${year}-${month}-${day} ${hours}-${minutes}-${seconds}`;
    g = `${year}-${month}-${day}`
    return dateTimeString;
}

// 上下架
let statust = ref('');
function funstatus(e) {
    console.log(e);

    if (e.status == '1') {
        statust.value = '0';
    } else if (e.status == '0') {
        statust.value = '1';
    }
    console.log(statust.value);

    lark_list_shop_edit({ token: tokens.token, uid: tokens.userinfo.id }, {
        userid: tokens.userinfo.id,
        id: e.id,
        type_id: e.type_id,
        status: statust.value,
        state: 1,
        longitude: e.longitude,
        latitude: e.latitude,
        address_title: e.address_title,
        address: e.address,
        address_desc: e.address_desc,
        img: e.img,
        imgs: e.imgs,
        score: e.score,
        money: 0,
        title: e.title,
        time_desc: e.time_desc,
        tel: e.tel,
        tags: e.tags,
        uid: tokens.userinfo.id,
        adcode: ''
    }).then((res) => {
        console.log(res);

        if (res.code == '1') {

            ElMessage({
                message: '操作成功',
                type: 'success',
            });


            render();
        } else {

        }
    });
}

// 表单对象
const ruleForm = reactive({
    name: '',
    img: '',
    jqfl: '',
    jqry: '',
    jqdh: '',
    yysj: '',
    jqdz: '',
    jd: '',
    wd: '',
    dpdz: '',
    covers: '',
    introduce: '',
    mdbq: '',
    dzzy: '',
    option: '',
    switch: ''
});
const ruleFormRef = ref('');
const rules = reactive({
    mdbq: [
        {
            required: true,
            message: '请输入门店标签',
            trigger: 'blur',
        },
    ],
    dzzy: [
        {
            required: true,
            message: '请输入地址指引',
            trigger: 'blur',
        },
    ],
    option: [
        {
            required: true,
            message: '请选择门店类型',
            trigger: 'blur',
        },
    ],
    name: [
        {
            required: true,
            message: '请输入门店名称',
            trigger: 'blur',
        },
    ],
    jqfl: [
        {
            required: true,
            message: '请输入门店电话',
            trigger: 'blur',
        },
    ],
    jqry: [
        {
            required: true,
            message: '请输入营业时间',
            trigger: 'blur',
        }
    ],
    jqdh: [
        {
            required: true,
            message: '请输入门店地址',
            trigger: 'blur',
        },
    ],
    img: [
        {
            required: true,
            message: '请上传轮播图片',
            trigger: 'change',
        },
    ],
    yysj: [
        {
            required: true,
            message: '请输入简短地址',
            trigger: 'change',
        },
    ],
    dpdz: [
        {
            required: true,
            message: '请输入店铺地址',
            trigger: 'change',
        },
    ],
    jqdz: [
        {
            required: true,
            message: '请输入景点地址',
            trigger: 'change',
        },
    ],
    jd: [
        {
            required: true,
            message: '请输入经度',
            trigger: 'change',
        },
    ],
    wd: [
        {
            required: true,
            message: '请输入维度',
            trigger: 'change',
        },
    ],
    covers: [
        {
            required: true,
            message: '请上传图片',
            trigger: 'change',
        },
    ],
    introduce: [
        {
            required: true,
            message: '请输入简介',
            trigger: 'change',
        },
    ],

});
// 点击确认或编辑
const submitForm = (formEl) => {
    console.log(iitimg.value);
    console.log(ruleForm.option);
    if (!formEl) return;
    formEl.validate((valid) => {
        if (valid) {
            if (statused.value == '2') {
                console.log(ruleForm);
                lark_list_shop_edit({ token: tokens.token, uid: tokens.userinfo.id }, {
                    userid: tokens.userinfo.id,
                    id: ids.value,
                    type_id: ruleForm.option,
                    status: stattess.value,
                    state: 1,
                    longitude: ruleForm.jd,
                    latitude: ruleForm.wd,
                    address_title: ruleForm.yysj,
                    address: ruleForm.jqdh,
                    address_desc: ruleForm.dzzy,
                    img: ruleForm.covers,
                    imgs: iitimg.value.join(','),
                    score: ruleForm.dpdz,
                    money: 0,
                    title: ruleForm.name,
                    time_desc: ruleForm.jqry,
                    tel: ruleForm.jqfl,
                    tags: ruleForm.mdbq,
                    uid: tokens.userinfo.id,
                    adcode: ''
                }).then((res) => {
                    if (res.code == '1') {
                        ElMessage({
                            message: '编辑成功',
                            type: 'success',
                        });
                        setTimeout(() => {
                            activeStatud.value = false;
                            activeStatu.value = true;
                            fileList.value = []
                        }, 1200);
                        render();
                    } else {
                        ElMessage({
                            message: '编辑失败，不能和原数据一致',
                            type: 'warning',
                        });
                    }
                });
            }
        }
        else {
            ElMessage({
                message: '编辑失败',
                type: 'error',
            });
        }
    });
};
// 编辑用的id
const ids = ref('');
const disableds = ref(true);
// 关闭新增
const closes = (formEl) => {
    console.log(formEl);
    activeStatu.value = true
    activeStatud.value = false
    formEl.resetFields();
    formEl.clearValidate()
    dialogTableVisible.value = false;
    files.value = false;
    ruleForm.name = ''
    fileList.value = []
};
// 点击编辑
function edit(item) {
    console.log(item);
    lati.value = item.latitude;
    longi.value = item.longitude;
    console.log(lati.value);
    // 重新初始化地图以应用新坐标
    initMap().then(newMap => {
        map = newMap;
        loadPluginsAndBindEvents(map);
    });
    stattess.value = item.status
    if (item.status == 1) {
        ruleForm.switch = true
    } else {
        ruleForm.switch = false
    }
    // 封面图片回显
    fileListt.value = [{
        url: testName + item.img,
    }]
    for (let i = 0; i < item.imgs.split(',').length; i++) {
        // console.log(item.banner.split(','));
        fileListQW.value.push(testName + item.imgs.split(',')[i])
        fileList.value.push(
            {
                url: testName + item.imgs.split(',')[i],
            });
    }
    // 门店分类id
    ruleForm.option = item.type_id
    // 评分
    ruleForm.dpdz = item.score
    // 名称
    ruleForm.name = item.title
    // 手机号
    ruleForm.jqfl = item.tel
    // 营业时间
    ruleForm.jqry = item.time_desc
    // 地址
    ruleForm.jqdh = item.address
    // 简短地址
    ruleForm.yysj = item.address_title
    // 地址指引
    ruleForm.dzzy = item.address_desc
    // 门店标签
    ruleForm.mdbq = item.tags

    // Object.assign(ruleForm, item);
    ids.value = item.id;
    activeStatud.value = true
    activeStatu.value = false
    ruleForm.jd = item.longitude
    ruleForm.wd = item.latitude
    iitimg.value = item.imgs.split(',')

    Delete.value = item.imgs
    ruleForm.covers = item.img
    ruleForm.img = item.imgs.split(',')

    disableds.value = false;
    statused.value = '2';
}
// 点击上传出现弹窗
function deletes(item) {
    console.log(item);
    centerDialogVisible.value = true;
    deleteids.value = item.id;
}

const deleteids = ref('');
const centerDialogVisible = ref(false);

// 确认删除
function deleteid() {
    activeDel(
        {
            token: tokens.token,
            uid: tokens.userinfo.id,
        },
        {
            userid: tokens.userinfo.id,
            id: deleteids.value,
        }
    ).then((res) => {
        if (res.code == '1') {
            centerDialogVisible.value = false;
            ElMessage({
                message: '删除成功',
                type: 'success',
            });
            render();
        }
    });
}
// 分类名称搜索
function filters() {
    let a = [];
    activeList.value = copyList.value.filter(item => {
        // 判断是否满足搜索条件
        if (String(item.title).indexOf(String(inputed.value)) > -1 &&
            String(item.tel).indexOf(String(tel.value)) > -1
        ) {
            return activeList.value;
        }
    });
    currentPage.value = 1
}
const shows = ref(false);
// 删除批量
// 全选单选
const SelectArr = ref([])
const All_Delete = ref([])
const handleSelectionChange = (val) => {
    All_Delete.value = []
    SelectArr.value = val
    SelectArr.value.forEach(item => {
        console.log(item);
        All_Delete.value.push(item.id)
    })
    console.log(All_Delete.value);
}
// 批量删除
// 批量删除
const centerDialogVisiblet = ref(false)
const st = ref([])
function deleList() {
    st.value = []
    console.log(All_Delete.value);
    st.value.push(All_Delete.value)
    if (All_Delete.value == '') {
        ElMessage({
            message: '请勾选要删除的游玩',
            type: 'warning',
        })
    } else {
        centerDialogVisiblet.value = true
    }
}
// 确认批量删除
const deleteid_t = () => {
    activeDel({
        token: tokens.token,
        uid: tokens.userinfo.id
    }, {
        userid: tokens.userinfo.id,
        id: st.value.join(','),
    }).then(res => {
        console.log(res, '删除成功或失败回调');
        centerDialogVisiblet.value = false;
        render();
        ElMessage({
            message: '删除成功',
            type: 'success',
        })
    })
}
</script>

<style>
/* 引入外部资源 */
@import url("https://cache.amap.com/lbs/static/main1119.css");

/* 基础样式 */
.text {
    font-size: 14px;
}

.item {
    margin-bottom: 18px;
}

.clearfix:before,
.clearfix:after {
    display: table;
    content: '';
}

.clearfix:after {
    clear: both;
}

.box-card {
    display: flex;
    height: 300px;
    width: 90%;
}

.handle {
    display: flex;
    align-items: center;
    justify-content: center;
}

.paging {
    display: flex;
    justify-content: center;
    margin-top: 10px;
    height: 70px;
}

.flex {
    display: flex;
    align-items: center;
    padding-bottom: 10px;
}

.flexBox {
    display: flex;
    width: 100%;
    align-items: center;
}

/* 表格样式 */
.data-table {
    margin-top: 10px;
    width: 100%;
}

.table-image {
    width: 40px;
    height: 40px;
}

.edit-btn {
    color: rgba(64, 158, 255, 1);
    cursor: pointer;
}

/* 搜索区域样式 */
.search-container {
    padding: 10px;
}

.search-label {
    width: 220px;
}

.search-input {
    width: 220px;
}

.ml-5 {
    margin-left: 20px;
}

.mb-10 {
    margin-bottom: 40px;
}

.mb-8 {
    margin-bottom: 30px;
}

/* 编辑区域样式 */
.edit-container {
    padding: 10px;
}

.edit-card {
    width: 96%;
    margin-left: 2%;
    margin-top: 1%;
    position: relative;
    height: auto;
}

.edit-title {
    padding: 10px;
}

.divider {
    width: 100%;
    height: 1px;
    background-color: rgba(195, 195, 195, 1);
}

.form-container {
    margin-top: 50px;
    margin-left: 100px;
}

.form-wrapper {
    width: 90%;
}

.form-row {
    display: flex;
    width: 100%;
    justify-content: space-between;
}

.form-col {
    width: 48%;
}

.form-item {
    width: 100%;
}

.full-width-input {
    width: 100%;
}

.phone-input {
    width: 90%;
}

/* 地图样式 */
.map-search-container {
    width: 90%;
    display: flex;
    align-items: center;
	height: 200px;
}

.map-search-input {
    width: 50%;
}

.map-container {
    width: 90%;
    height: 200px;
    margin-top: 50px;
}

/* 上传组件样式 */
.el-upload-list--picture-card {
    --el-upload-list-picture-card-size: 100px;
    display: inline-flex;
    flex-wrap: wrap;
    margin: 0;
}

.el-upload--picture-card {
    --el-upload-picture-card-size: 99px;
    align-items: center;
    background-color: var(--el-fill-color-lighter);
    border: 1px dashed var(--el-border-color-darker);
    border-radius: 6px;
    box-sizing: border-box;
    cursor: pointer;
    display: inline-flex;
    height: var(--el-upload-picture-card-size);
    justify-content: center;
    vertical-align: top;
    width: var(--el-upload-picture-card-size);
}

/* 自定义上传组件样式 */
.custom-upload {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    max-width: 350px;
}

/* 设置每个上传项的固定大小 */
.custom-upload .el-upload,
.custom-upload .el-upload-list__item {
    width: calc((100% - 20px) / 3);
    /* 一行显示3个，减去间距 */
    width: 100px;
    height: 100px;
    /* 固定高度 */
    margin-bottom: 10px;
    /* 行间距 */
}

/* 确保每行最多显示3个元素 */
.custom-upload .el-upload-list__item:nth-child(3n+1) {
    clear: left;
    /* 每3个元素强制换行 */
}

/* 上传按钮样式 */
.custom-upload .el-upload--picture-card {
    order: 999;
    /* 将上传按钮放在最后 */
}

/* 当有3个或更多图片时，确保上传按钮正确显示 */
.custom-upload .el-upload-list__item:nth-child(3)~.el-upload--picture-card {
    clear: left;
    /* 当有3个图片时，上传按钮换行显示 */
}

/* 对话框样式 */
.dialog-content {
    font-size: 16px;
    padding-bottom: 20px;
}

.dialog-footer {
    display: flex;
    justify-content: end;
}

.dialog-image {
    width: 100%;
    height: 100%;
}

/* 表单操作按钮 */
.form-actions {
    position: absolute;
    bottom: 60px;
    right: 40px;
}
</style>    